<template>
  <el-container>
    <el-aside width="220px">
      <el-menu
          default-active="1"
          class="el-menu-vertical-demo sub-nav"
          @open="menuOpen"
      >
        <el-sub-menu :index="subjectIndex" :key="subjectIndex"
                     v-for="(subjectItem,subjectIndex) in treeData">
          <template #title>
            <span>{{ subjectItem.label }}</span>
          </template>
          <el-menu-item @click="menuItemClick(subjectItem.value,campusItem.value)"
                        :index="subjectIndex+'-'+campusIndex"
                        :key="campusIndex"
                        v-for="(campusItem,campusIndex) in subjectItem.children">
            {{ campusItem.label }}
          </el-menu-item>
        </el-sub-menu>
      </el-menu>

    </el-aside>
    <el-main>

      <avue-crud v-model="form"
                 class="basis-xl right-view"
                 :option="option"
                 :page="page"
                 @on-load="onLoad"
                 @row-click="rowClick"
                 :data="data">

        <template #menu-left="{}">
          <el-button type="success"
                     @click="openExamTimeSettingFrom">配置考试时间
          </el-button>
          <el-button type="success"
                     @click="exportClick">预览
          </el-button>
          <el-button type="success"
                     @click="openExportPicker">导出选择
          </el-button>
        </template>
      </avue-crud>

    </el-main>
    <el-drawer
        v-model="showTimeSetting"
        title="考试时间设置"
    >
      <span>{{ currentSubject ? currentSubject.name : '' }}-{{ currentCampus ? currentCampus.name : '所有校区' }}</span>

      <exam-time-setting-form @submit="onExamTimeSettingSubmit" v-model:data="timeSettingForm"/>

    </el-drawer>


  </el-container>


  <el-dialog
      v-model="dialogShow"
      :title="dialogSettings[dialogMode].title"
      :width="dialogSettings[dialogMode].width"
  >


    <export-preview-view v-show="dialogMode=='exportPreviewView'" ref="exportPreviewView"></export-preview-view>
    <!--    导出选择-->
    <export-picker v-show="dialogMode=='exportPicker'" ref="exportPicker"></export-picker>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogShow = false">取消</el-button>
        <el-button type="primary" @click="dialogSubmit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>


</template>

<script>
import {nextTick, reactive, ref, toRefs} from "vue";
import {useArrangeStore} from "@/store/arrangeStore";
import pinia from "@/store/store";
import {onActivated} from "@vue/runtime-core";
import {processAppConfig} from "@/util/appConfigUtil";
import _ from "lodash";
import ExamTimeSettingForm from "@/components/ExamTimeSettingForm";
import {buildExamTimeList} from "@/util/arrange";
import ExportPreviewView from "@/components/ExportPreviewView";
import {loadCustomVariableMap, processBatchItemData, replaceAllByMap} from "@/util/examArrangeUtil";
import ExportPicker from "@/components/ExportPicker";
import {exportDataToFile} from "@/util/exportUtil";

const appConfig = processAppConfig()

const arrangeStore = useArrangeStore(pinia)

export default {
  name: "ArrangeExportView",
  components: {ExportPreviewView, ExamTimeSettingForm, ExportPicker},
  setup: function () {
    const exportPreviewView = ref(null)
    const exportPicker = ref(null)

    const form = ref({})
    const topData = reactive({
      showTimeSetting: false,
      currentSubject: null,
      currentCampus: null,
      timeSettingForm: {
        ...appConfig.arrangeConfig.globalTimeSetting
      },
      dialogShow: false,
      exportPreviewShow: false,
      exportPreviewData: [],
      // timeSettingOption: {}
      dialogMode: 'exportPicker',
      dialogSettings: {
        'exportPicker': {
          title: "导出选择",
          width: '35%'
        },
        'exportPreviewView': {
          title: "导出预览",
          width: '90%'
        }
      },
      currentSelectRow: 0
    })
    const rightData = reactive({
      option: {
        index: true,
        addBtn: false,
        highlightCurrentRow: true,
        delBtn: false,
        rowKey: 'id',
        rowParentKey: 'pid',
        subjectTimeDataMap: new Map(),
        defaultExpandAll: true,
        column: [
          {
            label: '批次编号',
            prop: 'pid'
          },
          {
            label: '子批次编号',
            prop: 'id'
          },
          {
            label: '考场',
            prop: 'examHallName'
          },
          {
            label: '开始时间',
            prop: 'startTime',
            type: "time",
            format: "YYYY/MM/DD HH:mm"

          },
          {
            label: '结束时间',
            prop: 'endTime',
            type: "time",
            format: "YYYY/MM/DD HH:mm"
          }
        ]
      },
      data: [{
        name: '张三',
        sex: 12
      }, {
        name: '李四',
        sex: 13
      }],
      search: {},
      originData: [],
      filterData: [],
      pageData: [],
      page: {
        total: 1000,
        currentPage: 1,
        pageSize: 5,
        pageSizes: [5, 10, 15, 20, 50, 100]
      },
      currentSubject: ""
    })
    const leftSubjectTree = reactive({
      treeData: [
        {

          label: "计算机导论",
          value: "00004334",
          children: [
            {
              label: "花津校区",
              value: "00004334",
            },
            {
              label: "赭山校区",
              value: "00004334",
            }
          ]
        }
      ],
      subjects: [
        {
          label: "花津校区",
          value: "00004334",
        },
        {
          label: "赭山校区",
          value: "00004334",
        }
      ]
    })


    onActivated(() => {
      leftSubjectTree.treeData = buildLeftSubjectTree()
      console.log(leftSubjectTree.treeData)
    })

    function rowClick(row) {
      console.log(row)
      topData.currentSelectRow = row.$index
    }


    //展示弹窗
    function showDialog(mode) {
      topData.dialogShow = true;
      topData.dialogMode = mode;
    }

    function hideDialog() {
      topData.dialogShow = false;
    }

    //弹窗确定
    function dialogSubmit() {
      //关闭弹窗
      hideDialog()
      if (topData.dialogMode === 'exportPicker') {
        let formData = exportPicker.value.handleSubmit();

        console.log('formData', formData)
        let {subject, fileName} = formData
        subject.forEach(subjectCode => {
          exportToFile(subjectCode, fileName);
        })


      } else {
        exportPreviewView.value.handleSubmit();
      }

    }

    //打开导出选择
    function openExportPicker() {
      showDialog('exportPicker')
      console.log(arrangeStore.subjectList)
      nextTick(() => {
        exportPicker.value.openPicker({
          subject: arrangeStore.subjectList.map(item => {
            return {
              label: item.name,
              value: item.code,
            }
          }),
          campus: [
            {
              label: "花津校区",
              value: "00004334",
            },
            {
              label: "赭山校区",
              value: "00004335",
            }
          ]
        })


      })

    }

    //导出预览按钮单击
    function exportClick() {


      let subject = topData.currentSubject.code
      let campus = topData.currentCampus.code


      console.log('typeof campus', typeof campus)
      //第几批次
      let batchIndex = topData.currentSelectRow;

      console.log('batchIndex', topData.currentSelectRow)
      //展示预览表格
      showExportPreviewTable(createArrangeTable(subject, campus, batchIndex))
    }


    function exportToFile(subjectCode, fileNamePattern) {
      let subjectArrangeData = buildSubjectArrangeTableData(subjectCode)
      console.log('subjectArrangeData', subjectArrangeData)
      exportDataToFile(subjectArrangeData, getFileName(subjectCode, fileNamePattern))
    }


    function getFileName(subjectCode, fileNamePattern) {
      var map = new Map();
      loadCustomVariableMap(map)
      let subjectName = appConfig.dicts.subjects.find(item => item.value === subjectCode).label
      map.set('subjectName', subjectName);
      map.set('subject', subjectName);

      return replaceAllByMap(fileNamePattern, map)

    }

    //构建学校的考场安排表
    function buildSubjectArrangeTableData(subjectCode) {
      let subjectData = arrangeStore.arrangeData[subjectCode]

      let arrangeTableData = []
      for (let campusKey in subjectData) {

        let campusTimeArrangeData = getCacheDataOrCalc(subjectCode, campusKey)
        console.log('campusTimeArrangeData', campusTimeArrangeData)
        for (let i = 0; i < campusTimeArrangeData.length; i++) {
          console.log(`创建安排表 科目${subjectCode} 校区${campusKey} 批次${i}`)
          var arrangeTable = createArrangeTable(subjectCode, campusKey, i);
          arrangeTableData = arrangeTableData.concat(arrangeTable)
        }
      }
      return arrangeTableData;
    }

    //创建导出安排表 batchIndex arrangeStore.subjectCode.campusCode.batch.batchIndex
    function createArrangeTable(subjectCode, campusCode, batchIndex) {
      let cacheData = getCacheData(subjectCode, campusCode);

      let batchTimeData = cacheData.filter(item => item.batchIndex === batchIndex)

      return processBatchItemData(arrangeStore.arrangeData, subjectCode, campusCode, batchIndex, batchTimeData)
    }

    //打开导出预览表格
    function showExportPreviewTable(data) {
      topData.exportPreviewData = data;


      showDialog("exportPreviewView")
      nextTick(() => {
        exportPreviewView.value.loadData(data, {
          subject: topData.currentSubject.name
        })
      })

    }


    //考场批次合并
    function spanMethod({row, column, rowIndex, columnIndex}) {
      console.log(row, column, rowIndex,)
      if (columnIndex === 1) {

        if (row.rowSpan === row.topRowSpan) {
          return {
            rowspan: row.rowSpan,
            colspan: 1,
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    }


    //设置考试时间
    function openExamTimeSettingFrom() {
      topData.showTimeSetting = true;
      var subjectSettingElement = appConfig.arrangeConfig.subjectSetting[topData.currentSubject.code];
      topData.timeSettingForm = subjectSettingElement ? subjectSettingElement.timeSetting : appConfig.arrangeConfig.globalTimeSetting
    }

    //提交时间设置
    function onExamTimeSettingSubmit(data) {
      topData.showTimeSetting = false;

      var examTimeList = buildExamTimeList(data);


      console.log(examTimeList);

      let subject = topData.currentSubject.code


      var currentCampus = topData.currentCampus;


      //当前选择的学科
      var subjectData = []
      let subjectArrangeData = arrangeStore.arrangeData[subject];

      for (let campusKey in subjectArrangeData) {
        var campus = campusKey;

        if (currentCampus) {
          campus = currentCampus.code
          if (campus !== campusKey) {
            continue;
          }
        }

        var campusData = getCacheData(subject, campus)

        console.log(campusData)
        let sindex = 0;
        let startIndex = 0;

        for (let i = 0; i < campusData.length; i++) {
          if (campusData[startIndex].pid !== campusData[i].pid) {
            sindex++;
            startIndex = i;
          }
          campusData[i] = {
            ...campusData[i],
            ...examTimeList[sindex]
          }
        }


        //更新缓存数据
        setCacheData(subject, campus, campusData)
        subjectData = subjectData.concat(campusData)
      }


      //
      // //更新考试时间

      rightData.filterData = subjectData

      subPage(rightData.filterData)

    }


    //构建左侧的树
    function buildLeftSubjectTree() {
      var arrangeData = arrangeStore.arrangeData;

      return arrangeStore.subjectList.map(subject => {
        let children = []

        for (let campusKey in arrangeData[subject.code]) {

          var campus = appConfig.columnDefines.campus.dicMap.get(campusKey);
          children.push({
            label: campus,
            value: campusKey
          })
        }
        return {
          label: subject.name,
          value: subject.code,
          children,
        }
      })
    }

    function menuItemClick(subject, campus) {
      console.log(subject, campus)
      let subjectArrangeData = arrangeStore.arrangeData[subject];


      topData.currentCampus = {
        name: appConfig.columnDefines.campus.dicMap.get(campus),
        code: campus
      }


      topData.currentSubject = {
        name: appConfig.columnDefines.subjectName.dicMap.get(subject),
        code: subject
      }


      let campusData = subjectArrangeData[campus]

      // buildBatchTable(campusData.batch, campus)
      let data = getCacheDataOrCalc(subject, campus, campusData.batch)
      rightData.filterData = data
      subPage(data)
    }


    //数据分页
    function subPage(data) {
      //分页
      console.log("分页", data)
      let {currentPage, pageSize, total} = rightData.page
      // if (pageSize !== this.page.pageSize) {
      if (data.length !== total || rightData.pageData.length > 0 && (rightData.pageData[0].length !== pageSize || rightData.pageData[0] !== data[0])) {
        rightData.pageData = _.chunk(data, pageSize)
      }
      rightData.page.total = data.length;
      rightData.data = rightData.pageData[currentPage - 1]
    }

    function menuOpen(index, indexPath) {
      console.log(index, indexPath)

      let data = []
      let subject = arrangeStore.subjectList[index];
      //当前选择的学科
      topData.currentSubject = subject;
      topData.currentCampus = null;

      let subjectArrangeData = arrangeStore.arrangeData[subject.code];
      for (let campusKey in subjectArrangeData) {
        let campusData = subjectArrangeData[campusKey]
        console.log(subject, campusData.batch, subjectArrangeData)
        // buildBatchTable(campusData.batch, campusKey)

        data = data.concat(getCacheDataOrCalc(subject.code, campusKey, campusData.batch))
      }
      rightData.filterData = data
      subPage(data)
    }

    function onLoad(page) {
      let {pageSize, currentPage} = page
      rightData.page.currentPage = currentPage

      rightData.page.pageSize = pageSize
      subPage(rightData.filterData);
    }

    //设置缓存数据
    function setCacheData(subject, campus, data) {

      // console.log(rightData.subjectTimeDataMap)
      if (!rightData.subjectTimeDataMap) {
        rightData.subjectTimeDataMap = new Map()
      }
      var campusMap = rightData.subjectTimeDataMap.get(subject);
      if (!campusMap) {
        campusMap = new Map();
        rightData.subjectTimeDataMap.set(subject, campusMap)
      }

      return campusMap.set(campus, data)
    }

    //获取缓存数据
    function getCacheData(subject, campus) {
      // console.log(rightData.subjectTimeDataMap)
      if (!rightData.subjectTimeDataMap) {
        rightData.subjectTimeDataMap = new Map()
      }
      var campusMap = rightData.subjectTimeDataMap.get(subject);
      if (!campusMap) {
        campusMap = new Map();
        rightData.subjectTimeDataMap.set(subject, campusMap)
      }

      return campusMap.get(campus)
    }

    function getCacheDataOrCalc(subject, campus, arrangeBatch) {
      let campusData = getCacheData(subject, campus)


      if (!campusData) {
        if (!rightData.subjectTimeDataMap) {
          rightData.subjectTimeDataMap = new Map()
        }
        var campusMap = rightData.subjectTimeDataMap.get(subject);
        console.log("初次构建数据", subject, campus)
        campusData = buildBatchTable(arrangeBatch, campus)
        campusMap.set(campus, campusData)
      }
      return campusData;

    }


    //构建批次表格
    function buildBatchTable(arrangeBatch, campus) {
      let examHallMap = appConfig.examHallMap[campus];

      let data = [];
      arrangeBatch.forEach((batchItem, batchIndex) => {
        let id = campus + '-' + batchIndex;
        // let cnt = Object.keys(batchItem).length;

        var firstRow = true;
        let rowSpan = Object.keys(batchItem).length
        let index = 0;
        for (let examHallKey in batchItem) {
          let totalStudent = batchItem[examHallKey].length
          if (totalStudent > 0) {
            data.push({
              id: id + '-' + examHallKey,
              pid: id,
              startTime: '',
              endTime: '',
              rowSpan: firstRow ? rowSpan : 0,
              topRowSpan: rowSpan - index,
              examHallKey,
              batchIndex: batchIndex,
              examHallName: examHallMap.get(examHallKey).name
            })
            index++;
          }
          firstRow = false;
        }
      })
      return data;
    }

    //构建批次表格树
    function buildBatchTableTree(arrangeBatch, campus) {

      let examHallMap = appConfig.examHallMap[campus];
      return arrangeBatch.map((batchItem, batchIndex) => {
        let children = []
        let id = campus + '-' + batchIndex;

        for (let examHallKey in batchItem) {

          children.push({
            id: id + '-' + examHallKey,
            pid: id,
            startTime: '',

            examHallName: examHallMap.get(examHallKey).name
          })
        }
        return {
          id,
          examHallName: '',
          startTime: '',
          endTime: '',
          pid: -1,
          children,
          onLoad
        }
      })
    }

    return {
      form,
      ...toRefs(rightData),
      ...toRefs(leftSubjectTree),
      ...toRefs(topData),
      menuItemClick,
      menuOpen,
      subPage,
      onLoad,
      onExamTimeSettingSubmit,
      openExamTimeSettingFrom,
      spanMethod,
      buildBatchTableTree,
      exportClick,
      exportPreviewView,
      exportPicker,
      openExportPicker,
      dialogSubmit,
      rowClick
    }
  }
}
</script>

<style scoped>
.sub-nav {
  position: fixed;
  height: calc(100vh - 65px);
  overflow-y: auto;
  width: 220px;
}

.right-view {
  overflow-y: auto;
  height: calc(100vh - 65px);
}
</style>